#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun  8 14:58:42 2025

@author: fenghongli
"""

import pandas as pd
import os
from statsmodels.tsa.stattools import adfuller

input_dir = 'stock_returns'
output_csv = 'adf_results.csv'

results = []

# 遍收益率数据
for file in os.listdir(input_dir):
    if file.endswith('_returns.csv'):
        file_path = os.path.join(input_dir, file)
        try:
            df = pd.read_csv(file_path)
            ts_code = df['ts_code'].iloc[0]
            ret_series = df['ret'].dropna()  # 去除NaN

            # ADF检验
            adf_result = adfuller(ret_series)
            test_stat = adf_result[0]
            p_value = adf_result[1]
            is_stationary = '平稳（拒绝原假设）' if p_value < 0.05 else '非平稳（不拒绝原假设）'

            results.append({
                'ts_code': ts_code,
                '文件名': file,
                'ADF统计量': round(test_stat, 4),
                'p值': round(p_value, 4),
                '平稳性判断': is_stationary
            })
        except Exception as e:
            print(f"处理文件 {file} 出错：{e}")

# 保存结果为DataFrame并输出到CSV
results_df = pd.DataFrame(results)
results_df.to_csv(output_csv, index=False, encoding='utf-8-sig')

print(f"平稳性检验完成，结果已保存至：{output_csv}")
